package com.nio;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


public class TestOne {
	public static void main(String[] args) {
		try{
			File file = new TestOne().getFile("data/nio-data.txt");
		   RandomAccessFile aFile = new RandomAccessFile(file, "rw");
		    FileChannel inChannel = aFile.getChannel();

		    ByteBuffer buf = ByteBuffer.allocate(48);

		    int bytesRead = inChannel.read(buf);
		    //long byteLength = inChannel.size();
		    while (bytesRead != -1) {

		      System.out.println("Read " + bytesRead);
		      buf.flip();

		      while(buf.hasRemaining()){
		          System.out.print((char) buf.get());
		      }

		      buf.clear();
		      bytesRead = inChannel.read(buf);
		    }
		    aFile.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private File getFile(String fileName) {
        ClassLoader classLoader = getClass().getClassLoader();
        /**
        getResource()方法会去classpath下找这个文件，获取到url resource, 得到这个资源后，调用url.getFile获取到 文件 的绝对路径
        */
        URL url = classLoader.getResource(fileName);
        /**
         * url.getFile() 得到这个文件的绝对路径
         */
        System.out.println(url.getFile());
        File file = new File(url.getFile());
        System.out.println(file.exists());
        return file;
    }
}
